#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :get_jingdong_order.py
# Time  :2024/12/11 13:43
# Email :fortunatedong@163.com
# Author:by Adonli
import copy
import json
import os
import random
import time

import requests

import toml
from decimal import getcontext, Decimal
import re
from jingdong_order_synchronization_kuaipu.settings.logger import Loggings
from jingdong_order_synchronization_kuaipu.synchronization_kuaipu.search_shop_supply_map_api import get_SearchShopSupplyMap_datas
from jingdong_order_synchronization_kuaipu.synchronization_kuaipu.synchronization_kuaipu_order_api import SynchronizationKuaiPuOrderApi
from jingdong_order_synchronization_kuaipu.dingding_robot.messages_push import  MessagePush
from jingdong_order_synchronization_kuaipu.analyze_datas.save_jingdong_synchronization_datas import SaveJingdongSynchronizationDatas
from jingdong_order_synchronization_kuaipu.settings.error_handler import retry_on_exception
logs = Loggings()


class get_jingdong_order_datas():
    # def __init__(self, username, password, startTime, endTime,jingdong_cookie):
    #     self.username = username
    #     self.password = password
    #     self.jingdong_cookie = jingdong_cookie
    #     self.cfg = toml.load('settings/config.toml')
    #     self.order_url = self.cfg['JINGDONGORDERURL']['order_url']
    #     self.headers = {
    #         "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    #         "cookie": self.jingdong_cookie,
    #     }
    #     self.payload = {
    #         "startTime": startTime,
    #         "endTime": endTime,
    #         "_search": "false",
    #         "nd": int(round(time.time() * 1000)),
    #         "rows": 100,
    #         "page": 1,
    #         "sidx": "orderId asc, groupString asc,",
    #         "sord": "asc",
    #         "orderId": "",
    #         "sku": "",
    #         "poId": "",
    #         "roId": "",
    #         "shipNo": "",
    #         "phone": "",
    #         "orderState": 7,
    #         "businessType": "",
    #         "pin": "",
    #         "paymentType": "",
    #         "vendorStoreId": "",
    #         "ouId": "",
    #     }
    def __init__(self, username, password,jingdong_cookie,payload):
        self.username = username
        self.password = password
        self.jingdong_cookie = jingdong_cookie
        self.cfg = toml.load('settings/config.toml')
        self.order_url = self.cfg['JINGDONGORDERURL']['order_url']
        self.headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cookie": self.jingdong_cookie,
        }
        self.payload = payload

    def json_to_cookie(self,json_data):
        # 提取name和value对,并用=连接
        cookie_pairs = [f"{cookie['name']}={cookie['value']}" for cookie in json_data]

        # 用分号和空格连接所有cookie对
        cookie_string = "; ".join(cookie_pairs)

        return cookie_string
    @retry_on_exception(max_retries=3,delay=2)
    def get_jingdong_order_json(self):

        response = requests.post(self.order_url, headers=self.headers, data=self.payload)
        if response.status_code == 200:
            logs.info(f"请求京东订单接口成功；状态值为{response.status_code}")
        else:
            logs.info(f"请求京东订单接口失败；状态值为{response.status_code}")
        # logs.info(f"datas_json:{response.json()}")
        datas_json = response.json()["rows"]

        if datas_json:
            logs.info(f"已获取{len(datas_json)}京东订单")
        else:
            logs.debug("未获取到京东订单")
        return datas_json

    @retry_on_exception(max_retries=3, delay=2)
    def handle_jingdong_order_json(self):
        datas_json = self.get_jingdong_order_json()
        detail_consignee_name_address = "https://pdropship.jd.com/virtualNumber/getConsigneeInfo"
        detail_consignee_phone = "https://pdropship.jd.com/virtualNumber/bindVirtualNumber"
        jingdong_orders_messages = []
        for data in datas_json:
            jingdong_order_id = data["orderId"]
            form_data = {
                "orderId": jingdong_order_id,
            }
            detail_consignee_name_address_response = requests.post(detail_consignee_name_address, headers=self.headers,
                                                                   data=form_data)
            detail_consignee_name_addres_json = detail_consignee_name_address_response.json()["userdata"][
                "consigneeInfo"]
            jingdong_consignee_name = re.sub(r"\[[^\]]*\]", "",
                                             detail_consignee_name_addres_json["consigneeName"])
            jingdong_consignee_address = re.sub(r"\[[^\]]*\]", "",
                                                detail_consignee_name_addres_json[
                                                    "consigneeAddress"])
            detail_consignee_phone_response = requests.post(detail_consignee_phone, headers=self.headers,
                                                            data=form_data)
            detail_consignee_phone_json = detail_consignee_phone_response.json()["userdata"]["virtualNumberInfo"]
            jingdong_phone = detail_consignee_phone_json["virtualNumber"]
            order_create_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data["orderCreateDate"] / 1000))

            add_jingdong_order = {
                "branch_id": "金穗隆(广州)信息科技有限公司",
                "jingdong_business_model": "电商销售",
                "jingdong_order_id": jingdong_order_id,
                "jingdong_consignee_name": jingdong_consignee_name,
                "jingdong_consignee_address": jingdong_consignee_address,
                "jingdong_phone": jingdong_phone,
                "order_create_date": order_create_date
            }
            add_jingdong_order_body = []
            for detail_data in data["orderDetailList"]:
                jd_price = detail_data['jdPrice']
                procurement_single_price = detail_data["poPrice"]
                ware_num = detail_data["wareNum"]
                jd_total_price = jd_price * ware_num
                procurement_total_price = procurement_single_price * ware_num
                ware_name = detail_data["wareName"]
                sku = detail_data["sku"]
                add_jingdong_order_dict = {
                    # "jingdong_ware_name": ware_name,
                    "jingdong_sku": sku,
                    "jingdong_ware_brand": "",
                    "jingdong_ware_category": "",
                    "jingdong_ware_model": "",
                    "jingdong_ware_num": ware_num,
                    "jingdong_jd_price":jd_price,
                    "jingdong_jd_total_price": jd_total_price,
                    "jingdong_procurement_single_price": procurement_single_price,
                    "jingdong_procurement_total_price": procurement_total_price,
                }
                add_jingdong_order_body.append(add_jingdong_order_dict)
            requests_dict = {
                "add_jingdong_order": add_jingdong_order,
                "add_jingdong_order_bodys": {
                    "add_jingdong_order_body": add_jingdong_order_body
                }
            }
            jingdong_orders_messages.append(requests_dict)
        logs.info(f"jingdong_orders_messages:{jingdong_orders_messages}")
        return jingdong_orders_messages

    @retry_on_exception(max_retries=3, delay=2)
    def inspect_kuaipu_map(self, jingdong_orders_messages):
        synchronization_orders_messages = []
        no_synchronization_orders_messages = []
        message_status = True
        for jingdong_order_message in jingdong_orders_messages:
            add_kuaipu_order_body = []
            for add_jingdong_order_body in jingdong_order_message["add_jingdong_order_bodys"]["add_jingdong_order_body"]:
                logs.info(f"正在检验sku{add_jingdong_order_body["jingdong_sku"]}映射")
                message_status = True
                messages_list = get_SearchShopSupplyMap_datas(add_jingdong_order_body["jingdong_sku"]).execute()
                if not messages_list:
                    logs.debug(f"{jingdong_order_message["add_jingdong_order"]["jingdong_order_id"]}订单中sku{add_jingdong_order_body["jingdong_sku"]}未找到商城映射数据。")
                    no_synchronization_orders_messages.append(jingdong_order_message)
                    message_status = False
                    add_kuaipu_order_body = []
                    break
                else:
                    for message in messages_list:
                        logs.info(f"message:{message}")
                        for data in message["search_shop_supply_map_bodys"]["search_shop_supply_map_body"]:
                            add_kuaipu_order_dict = {
                                "kuaipu_trading_num": add_jingdong_order_body["jingdong_ware_num"],
                                "kuaipu_ware_code": data["kuaipu_ware_code"],
                                "kuaipu_ware_name": data["kuaipu_ware_name"],
                                "kuaipu_ware_category": data["kuaipu_ware_category"],
                                "kuaipu_ware_brand": data["kuaipu_ware_brand"],
                                "kuaipu_warehouse": "",
                                "kuaipu_Specification_model": data["kuaipu_Specification_model"],
                                "kuaipu_trading_unit": data["kuaipu_trading_unit"],
                                "kuaipu_ware_num": float(data["kuaipu_ware_num"]),
                                "kuaipu_price_ratio": data["kuaipu_price_ratio"],
                                "kuaipu_tax_procurement_single_price": add_jingdong_order_body["jingdong_procurement_single_price"],
                                "kuaipu_tax_ratio": "13.00",
                                "kuaipu_procurement_single_price": float(add_jingdong_order_body["jingdong_procurement_single_price"])/1.13,
                                "kuaipu_tax_price": float(add_jingdong_order_body["jingdong_procurement_single_price"])-float(add_jingdong_order_body["jingdong_procurement_single_price"])/1.13,
                                "kuaipu_tax_total_price": float(add_jingdong_order_body["jingdong_procurement_single_price"])*float(add_jingdong_order_body["jingdong_ware_num"]),
                                "kuaipu_total_price": (float(add_jingdong_order_body["jingdong_procurement_single_price"])/1.13)*float(add_jingdong_order_body["jingdong_ware_num"]),
                                "kuaipu_giveaway": data["kuaipu_giveaway"],
                                "kuaipu_Delivery_order": ""
                            }
                            add_kuaipu_order_body.append(add_kuaipu_order_dict)
            if message_status:
                jingdong_order_message["add_kuaipu_order_bodys"] = {"add_kuaipu_order_body":add_kuaipu_order_body}
                synchronization_orders_messages.append(jingdong_order_message)
        return synchronization_orders_messages,no_synchronization_orders_messages


    def synchronization_kuaipu_order(self):
        jingdong_orders_messages = self.handle_jingdong_order_json()
        synchronization_orders_messages, no_synchronization_orders_messages = self.inspect_kuaipu_map(jingdong_orders_messages)
        if no_synchronization_orders_messages:
            for i in no_synchronization_orders_messages:
                no_synchronization_json_data = json.dumps({"request": i}, ensure_ascii=False)
                no_synchronization_dict_data = json.loads(no_synchronization_json_data)
                SaveJingdongSynchronizationDatas(no_synchronization_dict_data).save_no_synchronization_orders_messages()
                MessagePush(no_synchronization_dict_data).failed_text_push()
                logs.info(f"no_synchronization_json_data:{no_synchronization_json_data}")
                time.sleep(1)

        for i in synchronization_orders_messages:
            json_data = json.dumps({"request":i},ensure_ascii=False)
            dict_data = json.loads(json_data)
            json_data_copy = copy.deepcopy(dict_data)
            del json_data_copy['request']['add_jingdong_order']['order_create_date']
            for i in json_data_copy['request']['add_jingdong_order_bodys']['add_jingdong_order_body']:
                del i["jingdong_jd_price"]
                del i["jingdong_jd_total_price"]
            # __________________________________________________UPDATE对应接口有服务规则，只需要传入京东商品数据___________________________________________________________
            del json_data_copy['request']['add_kuaipu_order_bodys']

            # __________________________________________________UPDATE对应接口有服务规则___________________________________________________________
            synchronization_json_data = json_data_copy
            logs.info(f"synchronization_json_data:{synchronization_json_data}")

            synchronization_result = SynchronizationKuaiPuOrderApi(synchronization_json_data).execute()
            logs.info(f"synchronization_result:{synchronization_result.json()}")
            if synchronization_result.json()['response']['flag'] is True:
                MessagePush(dict_data).success_text_push()
                SaveJingdongSynchronizationDatas(dict_data).save_synchronization_orders_messages()
            time.sleep(random.randint(1, 3))











